package com.cas.jms;

import com.cas.jms.parser.Parser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jms.config.JmsListenerContainerFactory;
import org.springframework.jms.config.JmsListenerEndpoint;
import org.springframework.jms.config.JmsListenerEndpointRegistry;
import org.springframework.jms.config.SimpleJmsListenerEndpoint;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.jms.TextMessage;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class JmsListenerManager {

    private static final Logger logger = LoggerFactory.getLogger("data-parse");
    @Resource
    private JmsListenerContainerFactory<?> factory;
    @Resource
    private ParserFactory parserFactory;

    private final Map<String, JmsListenerEndpointRegistry> registryMap = new ConcurrentHashMap<>();

    @PostConstruct
    private void init() {
        parserFactory.getAllParserNames().forEach(this::start);
    }

    private void start(String queueName) {
        JmsListenerEndpointRegistry registry;
        if (registryMap.containsKey(queueName)) {
            registry = registryMap.get(queueName);
            if (!registry.isRunning()) {
                registry.start();
                logger.info("[ActiveMQ]-[{}]-<启动侦听>", queueName);
            }

        } else {
            registry = registry(createEndpoint(queueName));
            registryMap.put(queueName, registry);
            registry.start();
            logger.info("[ActiveMQ]-[{}]-<启动侦听>", queueName);
        }
    }

    /**
     * 根据消息队列名称创建JMS侦听端点
     *
     * @param queueName 队列名称
     * @return JMS侦听端点
     */
    private JmsListenerEndpoint createEndpoint(String queueName) {
        SimpleJmsListenerEndpoint endpoint = new SimpleJmsListenerEndpoint();
        endpoint.setId(queueName);
        endpoint.setDestination(queueName);
        endpoint.setMessageListener(message -> {
            String s;
            try {
                if (message instanceof TextMessage) {
                    s = ((TextMessage) message).getText();
                    logger.info("[ActiveMQ]-[{}]-<发送数据>->[DataReceiver],数据:[{}]", queueName, s);
                    // 消息内容DataForm 选择解析器
                    Parser parser = parserFactory.getParser(queueName);
                    if(parser != null) {
                        parser.process(s);
                    } else {
                        logger.error("JmsListenerManager 侦听端点失败 请确认配置信息是否正确");
                    }
                }
            } catch (Exception e) {
                logger.error("[DataReceiver]-<接收数据异常>-异常信息：[{}]", e.getMessage());
            }
        });
        return endpoint;
    }

    /**
     * 创建JMS侦听端点注册单元
     *
     * @param endpoint JMS侦听端点
     * @return JMS侦听端点注册单元
     */
    private JmsListenerEndpointRegistry registry(JmsListenerEndpoint endpoint) {
        JmsListenerEndpointRegistry jmsListenerEndpointRegistry = new JmsListenerEndpointRegistry();
        jmsListenerEndpointRegistry.registerListenerContainer(endpoint, factory);
        return jmsListenerEndpointRegistry;
    }
}
